package com.yangcangclub.api.v1.merchandise.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yangcangclub.commons.annotation.*;
import com.yangcangclub.commons.config.SysConfig;
import com.yangcangclub.commons.exception.ApolloException;
import com.yangcangclub.commons.result.MessageEnum;
import com.yangcangclub.commons.result.ResultData;
import com.yangcangclub.commons.utils.*;
import com.yangcangclub.merchandise.bean.Product;
import com.yangcangclub.merchandise.service.ProductService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 商品controller
 * Created by 肖明明 on 2017/2/20.
 */
@Controller
@RequestMapping("/yangcangclub/v1/merchandise")
public class MerchandiseController {
    private static Logger logger = LoggerFactory.getLogger(MerchandiseController.class);

    @Autowired
    ProductService productService;
    @Autowired
    UserAuth userAuth;
    @Autowired
    public SysConfig sysConfig;

    @Autowired
    public RedisTemplate<Object,Object> redisTemplate;
    
    
    /*公共接口*/
    /** 根据ID获取商品详情*/
    @ResponseBody
    @RequestMapping(value = "/detail")
    @ApolloSecurity(auth ={ AuthEnum.USER,AuthEnum.ADMIN},limit = 50,time = TimeEnum.MINUTE)
    public ResultData getProductInfoById(@GetUser User user, int pid,  HttpServletResponse response){
        ResultData resultData ;
        try {
            //校验
            if(pid<1) throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            //业务
            Product pd=productService.getProductById(pid);
            if (pd==null) throw new ApolloException(MessageEnum.PRODUCT_NOT_EXIST);
            
            if(pd.getIsLimit()==2){//限购处理
//                Map m=Maps.newHashMap();
                Map m= BeanMapUtil.convertBean(pd);
//                m.put("list",pd);
                Date now=new Date();
                boolean b=pd.getStartTime().getTime()<now.getTime();
                b=b&&pd.getEndTime().getTime()>now.getTime();
                m.put("sellStatue", b?1:2);//1为可以卖，2为时间未到
                m.put("now",DateUtil.dateToStrWithTime(now));

                resultData = new ResultData(MessageEnum.SUCCESS,m);
            }else{
                resultData = new ResultData(MessageEnum.SUCCESS,pd);
            }
            
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

    /** 外部分享访问商品详情页*/
    @ResponseBody
    @RequestMapping(value = "/product/{path}/{pid}")
    @ApolloSecurity(auth ={ AuthEnum.PUBLIC},limit = 100,time = TimeEnum.MINUTE)
    public void getProductInfoById(@PathVariable String path, @PathVariable int pid,
                                     HttpServletRequest request, HttpServletResponse response){
        try {
            if(!"wechat".equals(path)||pid<1){//非微信路径
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.setContentType("text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("路径不合法，服务器拒绝响应");
                response.flushBuffer();
            }
            //有cookie,从cookie获取应用access_token，
            Cookie[] cookies = request.getCookies();
            if(cookies != null) {
                String accessToken = null;
                String openId = null;
                for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie = cookies[i];
                    if(StringUtil.isNotEmpty(accessToken)&&StringUtil.isNotEmpty(openId)) 
                        break;
                    if ("WX_TICKET_COOKIE_KEY".equals(cookie.getName())) 
                        accessToken = cookie.getValue();
                    if ("WX_OPENID_COOKIE_KEY".equals(cookie.getName())) 
                        openId = cookie.getValue();
                }
                //校验access_token是否有效
                if(StringUtil.isNotEmpty(accessToken)&&StringUtil.isNotEmpty(openId)) {
                    //验证cache系统access_token是否失效
                    Map<String,Object> map = userAuth.getUserFullInfoByAccessToken(accessToken);
                    //有效：生成商品详情页链接，客户端跳转
                    if(map!=null) {
                        String url="http://b.yangcangclub.com/yangcangclub/res/details_page.html?access_token="+accessToken+"&pid="+pid;
//                        String url="http://192.168.23.1:8080/yangcangclub/res/details_page.html?access_token="+accessToken+"&pid="+pid;
                        response.sendRedirect(url);
                    }
                }
            }
            //没有cookie或无效：生成微信登录url，客户端跳转
            response.setContentType("text/html; charset = utf-8");
            request.getSession();//增加这行代码用来解决session
            String pathL = request.getContextPath();
            String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+pathL+"/";
            //test:wx6e1640c9e5b72719   //product：wx191292d175b76f6d
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx191292d175b76f6d&" +
                    "redirect_uri=http%3a%2f%2fb.yangcangclub.com%2fyangcangclub%2fv1%2fmerchandise%2fwx%2fcallback/" +pid+
                    "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6e1640c9e5b72719&" +
//                    "redirect_uri=http%3a%2f%2f192.168.23.1:8080%2fyangcangclub%2fv1%2fmerchandise%2fwx%2fcallback/" +pid+
//                    "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                response.sendRedirect(url);
        
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 微信回调商品详情接口
     */
    @RequestMapping(value = "/wx/callback/{pid}", method = {RequestMethod.GET})
    public void wxTologinCallback(@RequestParam String code,@RequestParam String state,
                                    @PathVariable int pid,
                                    HttpServletRequest request,HttpServletResponse response,
                                    Model model) {
        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        String errorMsg = "";
        String userId = "";
        String openId = "";
        String buzAccessToken = "";

        if(StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(state)) {
            String appid = sysConfig.getWxappid();
            String secret = sysConfig.getWxsecret();
            //测试
//            appid = "wx6e1640c9e5b72719";
//            secret = "d4624c36b6795d1d99dcf0547af5443d";
            
            Map<String,Object> wxUserInfo = getWxUserInfo(code,state,appid,secret);

            if(wxUserInfo.size()>0) {
                openId = (String)wxUserInfo.get("openid");
                String buzThridLogin = sysConfig.getAjaxUrlHead()+"/user/third";
                Map<String,String>map= Maps.newHashMap();
                map.put("access_token",(String)wxUserInfo.get("access_token"));
                map.put("openid",(String)wxUserInfo.get("openid"));
                map.put("type","1");

                JSONObject jsonObject = HttpUtils.doJsonGet(buzThridLogin, map);
                int buzCode = (int)jsonObject.get("code");
                if(buzCode==1000) {
                    Map<String,String> data=(Map<String,String>)jsonObject.get("data");
                    buzAccessToken = (String)data.get("access_token");
                    String firstLogin = (String)data.get("is_first_login");
                    userId = (String)data.get("userId");
                    if(StringUtil.isEquals(firstLogin,"Y")) {
                        String buzUpdateUserInfo = sysConfig.getAjaxUrlHead()+"/user/update";
                        Map<String,String>param= Maps.newHashMap();
                        param.put("access_token",buzAccessToken);
                        if(StringUtil.isNotEmpty((String)wxUserInfo.get("nickname"))) {
                            param.put("name",(String)wxUserInfo.get("nickname"));
                        }
                        if(StringUtil.isNotEmpty((String)wxUserInfo.get("nickname"))) {
                            param.put("nickname",(String)wxUserInfo.get("nickname"));
                        }
                        if(StringUtil.isNotEmpty((String)wxUserInfo.get("headimgurl"))) {
                            param.put("photo",(String)wxUserInfo.get("headimgurl"));
                        }
                        if(null!=wxUserInfo.get("sex")) {
                            param.put("sex",wxUserInfo.get("sex")+"");
                        }
                        param.put("system_from","3");// 蛋卡系统
                        param.put("user_mark","2");// 关注用户
                        HttpUtils.doJsonGet(buzUpdateUserInfo, param);
                    }
                    Cookie cookie = new Cookie("WX_TICKET_COOKIE_KEY", buzAccessToken);
                    Cookie cookie2 = new Cookie("WX_OPENID_COOKIE_KEY", openId);
                    cookie.setMaxAge(60);//缓存1分钟
                    cookie2.setMaxAge(60);//缓存1分钟
                    response.addCookie(cookie);
                    response.addCookie(cookie2);
                } else {
                    errorMsg = "系统自动注册用户失败";
                    logger.error("----/wx/callback  系统自动注册用户失败:");
                }
            } else {
                errorMsg = "没有获取到微信用户信息";
                logger.error("----/wx/callback  没有获取到微信用户信息:");
            }
        }else {
            errorMsg = "与微信交互参数异常";
            logger.error("----/wx/callback  与微信交互参数异常:");
        }
        try {
            if(StringUtil.isNotEmpty(errorMsg)) {//登录失败，重复跳转
                //test:wx6e1640c9e5b72719   //product：wx191292d175b76f6d
                String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx191292d175b76f6d&" +
                        "redirect_uri=http%3a%2f%2fb.yangcangclub.com%2fyangcangclub%2fv1%2fmerchandise%2fwx%2fcallback/" +pid+
                        "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6e1640c9e5b72719&" +
//                    "redirect_uri=http%3a%2f%2f192.168.23.1:8080%2fyangcangclub%2fv1%2fmerchandise%2fwx%2fcallback/" +pid+
//                    "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
                response.sendRedirect(url);
            }else {//登录成功，跳转商品详情
                String url="http://b.yangcangclub.com/yangcangclub/res/details_page.html?access_token="+buzAccessToken+"&pid="+pid;
//                String url="http://192.168.23.1:8080/yangcangclub/res/details_page.html?access_token="+buzAccessToken+"&pid="+pid;
                response.sendRedirect(url);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 抽取微信返回的用户信息
     */
    private Map<String,Object> getWxUserInfo(String code,String state,String appid,String secret) {
        Map<String,Object>data= Maps.newHashMap();
        String requestAccessToken_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        Map<String,String>map= Maps.newHashMap();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("code",code);
        map.put("grant_type","authorization_code");
        JSONObject jsonObject =HttpUtils.doJsonGet(requestAccessToken_url, map);
        if(jsonObject.get("errcode") == null) {
            String access_token = (String)jsonObject.get("access_token");
            String openid = (String)jsonObject.get("openid");
            map.clear();
            String requestWxInfo_url = "https://api.weixin.qq.com/sns/userinfo";
            map.put("access_token",access_token);
            map.put("openid",openid);
            map.put("lang","zh_CN");
            JSONObject infoJsonObject =HttpUtils.doJsonGet(requestWxInfo_url, map);
            if(infoJsonObject.get("errcode") == null) {
                String nickname = EmojiFilterUtil.filterEmoji((String)infoJsonObject.get("nickname"));
                int sex = (int)infoJsonObject.get("sex");
                String province = (String)infoJsonObject.get("province");
                String city = (String)infoJsonObject.get("city");
                String country = (String)infoJsonObject.get("country");
                String headimgurl = (String)infoJsonObject.get("headimgurl");
                data.put("access_token", access_token);
                data.put("openid", openid);
                data.put("nickname", nickname);
                data.put("sex", sex);
                data.put("province",province);
                data.put("city",city);
                data.put("country",country);
                data.put("headimgurl",headimgurl);
            }
        }
        return data;
    }
    
    /*用户端*/

    /** 获取商品展示页商品列表 
//     * @param type   0 推荐商品（所有商品）；1富硒商品；2每日优礼；3限时购；4精选商品；5云南仓；6中设仓；7贵州仓
     * @param user
     * @param isLimit
     * @param orderSort  排序依据字段，0表示第一页，其他每次穿列表的最后一条记录的字段
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/show")
    @ApolloSecurity(auth = AuthEnum.USER,limit = 50,time = TimeEnum.MINUTE)
    public ResultData getShowProductList(@GetUser User user,
                                         int isLimit,
                                         @RequestParam(required = false,defaultValue = "0")int orderSort,
                                         @RequestParam(required = false,defaultValue = "10")int pageSize,
                                         @RequestParam(required = false,defaultValue = "0")int category
                                         ){
        ResultData resultData ;
        try {
            //校验
            if(isLimit!=1&&isLimit!=2)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(orderSort<0||pageSize<1)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            String categoryName="";
            switch (category){
                case 1:categoryName="富硒鸡蛋";break;
                case 2:categoryName="富硒蛋卡";break;
                case 3:categoryName="富硒鸡";break;
            }
            //业务
            List<Product> list=productService.getShowProductList(categoryName,isLimit,orderSort,pageSize);
            Map m=Maps.newHashMap();
            m.put("list",list);
            if(isLimit==2){//限购时做下处理
                if(list!=null&&list.size()>0) {
                    Product p=list.get(0);
                    Date now=new Date();
                    boolean b=p.getStartTime().getTime()<now.getTime();
                    b=b&&p.getEndTime().getTime()>now.getTime();
                    m.put("sellStatue", b?1:2);//1为可以卖，2为时间未到
                    m.put("now",DateUtil.dateToStrWithTime(now));
                }
            }
            resultData = new ResultData(MessageEnum.SUCCESS,m);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

    
    /*后台*/
    /** 添加商品*/
    @ResponseBody//todo
    @RequestMapping(value = "/add",method = {RequestMethod.POST,RequestMethod.GET})
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData addProduct(@GetUser User user,
             String productName,String category,String unitPriceStr,
             @RequestParam(defaultValue = "0")String showUnitPriceStr,
             String shippingStr,int inventory, String bannerUrl, String content,
             int status,
             @RequestParam(required = false,defaultValue = "")String subtitle,
             @RequestParam(required = false,defaultValue = "1")int isFuxi,
             @RequestParam(required = false,defaultValue = "1")int warehouseType,
             @RequestParam(required = false,defaultValue = "1")int isEveryday,
             @RequestParam(required = false,defaultValue = "1")int isConcentrate,
             @RequestParam(required = false,defaultValue = "1")int isLimit,
             @RequestParam(required = false,defaultValue = "")String startTime,
             @RequestParam(required = false,defaultValue = "")String endTime,
             @RequestParam(required = false,defaultValue = "100")int showInventory,
             String uuidTag,
                                 HttpServletResponse response){
        ResultData resultData ;
        try {

            if(!isDoTradeFirst(uuidTag)){
                return new ResultData(MessageEnum.IGNORE_RESPONSE);
            }
            //校验
            /*1、非空非零 2、过滤xss 3、取值范围 */
            if(StringUtil.isAllFullEmpty(content))throw new ApolloException(MessageEnum.PARMA_IS_EMPTY);
//            content=StringUtil.filterXSS(content);
//            if(StringUtil.isAllFullEmpty(content))throw new ApolloException(MessageEnum.PARMA_IS_EMPTY);
            content=content.trim();//去除两端空格
            if(StringUtil.isAllValueContainEmpty(productName,bannerUrl,content,
                    unitPriceStr,showUnitPriceStr,shippingStr ))
                throw new ApolloException(MessageEnum.PARMA_IS_EMPTY);
            if(!BigDecimalUtil.isGreaterThan(unitPriceStr,"0")||!BigDecimalUtil.isGreaterThanOrEqualTo(showUnitPriceStr,"0")
                    ||!BigDecimalUtil.isGreaterThanOrEqualTo(shippingStr,"0"))
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(inventory<0) throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(status!=1&&status!=2&&status!=3)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);

            if(isFuxi!=1&&isFuxi!=2)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(warehouseType!=1&&warehouseType!=2&&warehouseType!=3
                    &&warehouseType!=4)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(isEveryday!=1&&isEveryday!=2)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(isConcentrate!=1&&isConcentrate!=2)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(isLimit!=1&&isLimit!=2)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(showInventory<0) throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(!"".equals(startTime)||!"".equals(endTime)){
                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    formatter.parse(startTime);
                    formatter.parse(endTime);
                } catch (ParseException e) {
                    throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
                }
            }
            if(isLimit==2){//限购商品
                isFuxi=warehouseType=isEveryday=isConcentrate=1;
                if(StringUtil.isAllValueContainEmpty(startTime,endTime))
                    throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            }
            if(isFuxi==2){warehouseType=1;}//排他
            if(warehouseType>1){isFuxi=1;}//排他

            BigDecimal unitPrice=new BigDecimal(unitPriceStr).setScale(2,BigDecimal.ROUND_DOWN);
            BigDecimal showUnitPrice=new BigDecimal(showUnitPriceStr).setScale(2,BigDecimal.ROUND_DOWN);
            BigDecimal shipping=new BigDecimal(shippingStr).setScale(2,BigDecimal.ROUND_DOWN);
            
                    //业务 
            int id=productService.addProduct(productName,category,unitPrice,showUnitPrice,shipping,
                    inventory, bannerUrl, content,status,user.getId(),user.getName(),
            isFuxi,isEveryday,isConcentrate,isLimit,
            startTime,endTime,showInventory,subtitle,warehouseType);

            resultData = new ResultData(MessageEnum.SUCCESS,id);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }
    
    /** 修改商品信息，不包括库存商品状态，包括基本信息和产量、价格、运费、排序*/
    @ResponseBody
    @RequestMapping(value = "/update")
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData updateProductInfo(@GetUser User user,int pid,
            String productName,String category,String unitPriceStr,
            @RequestParam(defaultValue = "0")String showUnitPriceStr,
            String shippingStr, String bannerUrl, String content,
            @RequestParam(required = false,defaultValue = "")String subtitle,
            @RequestParam(required = false,defaultValue = "1")int isFuxi,
            @RequestParam(required = false,defaultValue = "1")int warehouseType,
            @RequestParam(required = false,defaultValue = "1")int isEveryday,
            @RequestParam(required = false,defaultValue = "1")int isConcentrate,
            @RequestParam(required = false,defaultValue = "1")int isLimit,
            @RequestParam(required = false,defaultValue = "")String startTime,
            @RequestParam(required = false,defaultValue = "")String endTime,
            @RequestParam(required = false,defaultValue = "100")int showInventory,
                                        HttpServletResponse response){
        ResultData resultData ;
        try {
            /*1、非空非零 2、过滤xss 3、取值范围 */
//            content=StringUtil.filterXSS(content);
            if(StringUtil.isAllValueContainEmpty(productName,bannerUrl,content,
                    unitPriceStr,showUnitPriceStr,shippingStr ))
                throw new ApolloException(MessageEnum.PARMA_IS_EMPTY);
            if(!BigDecimalUtil.isGreaterThan(unitPriceStr,"0")||!BigDecimalUtil.isGreaterThanOrEqualTo(showUnitPriceStr,"0")
                    ||!BigDecimalUtil.isGreaterThanOrEqualTo(shippingStr,"0"))
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(!"".equals(startTime)||!"".equals(endTime)){
                try {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    formatter.parse(startTime);
                    formatter.parse(endTime);
                } catch (ParseException e) {
                    throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
                }
            }
            if(warehouseType!=1&&warehouseType!=2&&warehouseType!=3
                    &&warehouseType!=4)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);

//            if(isLimit==2){//限购商品
//                if(StringUtil.isAllValueContainEmpty(startTime,endTime))
//                    throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
//            }

            if(isFuxi==2){warehouseType=1;}//排他
            if(warehouseType>1){isFuxi=1;}//排他
            
            BigDecimal unitPrice=new BigDecimal(unitPriceStr);
            BigDecimal showUnitPrice=new BigDecimal(showUnitPriceStr);
            BigDecimal shipping=new BigDecimal(shippingStr);

            //业务
            productService.updateProductInfo(pid,productName,category,unitPrice,
                    showUnitPrice,shipping, bannerUrl, content, 
                    isFuxi,isEveryday,isConcentrate,isLimit,
                    startTime,endTime,showInventory,subtitle,warehouseType);
            resultData = new ResultData(MessageEnum.SUCCESS);
            
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }
    
//    /**修改库存*/
//    @ResponseBody
//    @RequestMapping(value = "/update/inventory")
//    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
//    public ResultData updateProductInventory(@GetUser User user,int pid,int formerInventory, 
//                                        int inventory,
//                                        HttpServletResponse response){
//        ResultData resultData ;
//        try {
//            //校验 
//            if(inventory<0) throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR); 
//
//            Map<String,String> map= Maps.newHashMap();
//
//            //业务
//
//            resultData = new ResultData(MessageEnum.SUCCESS);
//        }  catch (ApolloException apoEx) {
//            resultData=new ResultData(apoEx);
//        }catch (Exception e) {
//            logger.error(e.getMessage(), e);
//            resultData=new ResultData(e);
//        }
//        return resultData;
//    }
    
    /**修改商品状态*/
    @ResponseBody
    @RequestMapping(value = "/update/status")
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData updateProductStatus(@GetUser User user,int pid,int status,
                                             HttpServletResponse response){
        ResultData resultData ;
        try {
            //校验 
            if(status!=1&&status!=2&&status!=3)throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            
            //业务
            productService.updateProductionStatusById(pid,status);            

            resultData = new ResultData(MessageEnum.SUCCESS);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }
    
    /** 管理平台获取商品列表分页*/
    @ResponseBody
    @RequestMapping(value = "/list/page")
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData getPagenationProductList(@GetUser User user,
               @RequestParam(required=false,defaultValue = "1")int pageNum,
               @RequestParam(required=false,defaultValue = "10")int pageSize,
               @RequestParam(required=false,defaultValue = "0") int limitStatus,
               @RequestParam String isLimit,
               HttpServletResponse response){
        ResultData resultData ;
        try {
            //校验
            Map map = Maps.newHashMap();
            map.put("isLimit",isLimit);
            switch (limitStatus){
                case 1:
                    map.put("startTimeBegin",new Date());
                    break;
                case 2:
                    map.put("startTimeEnd",new Date());
                    map.put("endTimeBegin",new Date());
                    break;
                case 3:
                    map.put("endTimeEnd",new Date(

                    ));
                    break;
            }
            //业务
            Map m=productService.getPagenationProductList(pageNum,pageSize,map);

            resultData = new ResultData(MessageEnum.SUCCESS,m);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

    /**修改商品orderSort*/ //upOrDown  1上，2下
    @ResponseBody
    @RequestMapping(value = "/update/sort")
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData changeProductOrderSort(@GetUser User user,
                 int pid,int orderSort,int upOrDown,
               HttpServletResponse response){
        ResultData resultData ;
        try {
            //校验
            if(pid<1||orderSort<1)
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(upOrDown!=1&&upOrDown!=2)
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            
            //业务
            productService.updateProductOrderSort(pid,orderSort,upOrDown);

            resultData = new ResultData(MessageEnum.SUCCESS);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

    /**
     * 修改商品库存
     * @param pid
     * @param type 1加；2减
     * @param step 
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update/inventory")
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData changeProductInventory(@GetUser User user,
                 int pid,int type,int step,
                 HttpServletResponse response){
        ResultData resultData ;
        try {
            //校验
            if(pid<1||step<1)
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            if(type!=1&&type!=2)
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);

            if(type==2){
                step=0-step;
            }
            //业务
            boolean b=productService.reduceInventoriesById(pid,step);
            if(b){
                resultData = new ResultData(MessageEnum.SUCCESS);
            }else{
                throw new ApolloException(MessageEnum.TRY_AGAIN);
            }
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

    /**
     * 修改限购商品限购时间
     * @param pid
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update/limit/time")
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData changeLimitProductTime(@GetUser User user,
                     int pid,String startTime,String endTime,
                     HttpServletResponse response){
        ResultData resultData ;
        try {
            //校验
            if(StringUtil.isAllValueContainEmpty(startTime,endTime))
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            try {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                formatter.parse(startTime);
                formatter.parse(endTime);
            } catch (ParseException e) {
                throw new ApolloException(MessageEnum.PARMA_FORMAT_ERROR);
            }
                
            //业务
            boolean b=productService.changeLimitProductTime(pid,startTime,endTime);
            
            if(b){
                resultData = new ResultData(MessageEnum.SUCCESS);
            }else{
                throw new ApolloException(MessageEnum.TRY_AGAIN);
            }
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }
    

    /**
     * 下单接口幂等保证，第一次可以执行后面的不能执行。防止重复下单
     * @param token
     * @return
     */
    public boolean isDoTradeFirst(String token){
        if(StringUtil.isAllFullEmpty(token)){throw new ApolloException(MessageEnum.PARMA_RANGE_ERROR);}
        BoundValueOperations bvo = redisTemplate.boundValueOps(token);
        int expireSeconds=60;//1分钟token过期
        //判断是否存在token
        if( bvo.setIfAbsent(1)) {
            bvo.expire(expireSeconds, TimeUnit.SECONDS);
            return true;
        }else{
            return false;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/isShowModule")
    @ApolloSecurity(auth = AuthEnum.PUBLIC,limit = 50,time = TimeEnum.MINUTE)
    public ResultData isShowModule(@GetUser User user){
        ResultData resultData ;
        try {
            //业务
            boolean b = productService.limitProductModuleStatus();
            resultData = new ResultData(MessageEnum.SUCCESS,b);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

    @ResponseBody
    @RequestMapping(value = "/updateIsShowModule",method = {RequestMethod.POST})
    @ApolloSecurity(auth = AuthEnum.ADMIN,limit = 50,time = TimeEnum.MINUTE)
    public ResultData updateIsShowModule(@GetUser User user,String status){
        ResultData resultData ;
        try {
            //业务
            boolean s=status.equals("true")?true:false;
            boolean b = productService.setLimitProductModuleStatus(s);
            resultData = new ResultData(MessageEnum.SUCCESS,b);
        }  catch (ApolloException apoEx) {
            resultData=new ResultData(apoEx);
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultData=new ResultData(e);
        }
        return resultData;
    }

}
